﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace MishraReader
{
    public interface ISettingsManager
    {
        Settings Settings { get; }
        void Persist();
    }

    public class SettingsManager : ISettingsManager
    {
        private readonly XmlSerializer _serializer = new XmlSerializer(typeof(Settings));

        public SettingsManager()
        {
            var file = SettingsFile;
            try
            {
                if (!File.Exists(file))
                    return;


                using (var reader = new StreamReader(file))
                {
                    Settings = _serializer.Deserialize(reader) as Settings;
                }
            }
            catch
            {
            }
            finally
            {
                if (Settings == null)
                {
                    Settings = new Settings();
                }
                else
                {
                    Settings.IsNewOne = false;
                }
            }
        }

        public Settings Settings { get; private set; }


        public void Persist()
        {
            if (!Directory.Exists(ConfigFolder))
                Directory.CreateDirectory(ConfigFolder);

            try
            {
                using (var writer = new StreamWriter(SettingsFile))
                {
                    _serializer.Serialize(writer, Settings);
                }
            }
            catch
            {
            }
            finally
            {
                if (Settings == null) Settings = new Settings();
            }
        }

        public static string ConfigFolder
        {
            get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MishraReader"); }
        }

        public static string SettingsFile
        {
            get { return Path.Combine(ConfigFolder, "mishrareader.settings"); }
        }
    }
}